<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'add' ? '新增' : pageType === 'edit' || repairRecord === true ? '编辑' : '详情'}-维修记录`"
		width="800px"
		:show-cancel-btn="pageType !== 'detail'"
		:show-confirm-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		@on-cancel="onVisibleChange(false)"
		@on-close="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail'" label-width="100px" :show-message="false">
			<el-row class="flex-start-center-wrap">
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="日期" prop="belongDate">
						<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.belongDate || '无' }}</span>
						<jk-date-picker v-else v-model="ruleForm.belongDate" size="medium" placeholder="日期" class="width-100-percent" clearable></jk-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item class="margin-bottom-10" label="设备名称" prop="machineId">
						<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.machineName || '无' }}</span>
						<remote-search-machine-input
							v-else
							placeholder="设备名称"
							:disabled="repairRecord"
							only-key="machineId"
							query-name="machineName"
							:form-data="ruleForm"
							@on-select="onSelectMachineChange"
						></remote-search-machine-input>
					</el-form-item>
				</el-col>
			</el-row>
			<jk-divider-card title="维修信息" placement="center" class="margin-top-20">
				<el-row class="flex-start-center-wrap">
					<el-col :span="24">
						<el-form-item class="margin-bottom-10" label="维修时间" prop="timeRange">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.timeRange && ruleForm.timeRange.length ? `${ruleForm.timeRange[0]} ~ ${ruleForm.timeRange[1]}` : '无' }}</span>
							<jk-date-picker v-else v-model="ruleForm.timeRange" size="medium" type="datetimerange" placeholder="维修时间" class="width-100-percent" clearable></jk-date-picker>
						</el-form-item>
					</el-col>
					<!--<el-col :span="12">
                        <el-form-item class="margin-bottom-10" label="维修开始时间" prop="beginTime">
                            <span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.beginTime || '无' }}</span>
                            <jk-date-picker :picker-options="startPickerOption" v-else v-model="ruleForm.beginTime" size="medium" type="datetime" placeholder="维修开始时间" class="width-100-percent" clearable></jk-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item class="margin-bottom-10" label="维修结束时间" prop="endTime">
                            <span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.endTime || '无' }}</span>
                            <jk-date-picker :disabled="!ruleForm.beginTime" :picker-options="endPickerOption" v-else v-model="ruleForm.endTime" size="medium" type="datetime" placeholder="维修结束时间" class="width-100-percent" clearable></jk-date-picker>
                        </el-form-item>
                    </el-col>-->
					<el-col :span="24">
						<el-form-item class="margin-bottom-10" label="故障现象">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.faultDescription || '无' }}</span>
							<jk-input v-else v-model="ruleForm.faultDescription" type="textarea" :rows="2" placeholder="" />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item class="margin-bottom-10" label="故障诊断">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.faultDiagnosis || '无' }}</span>
							<jk-input v-else v-model="ruleForm.faultDiagnosis" type="textarea" :rows="2" placeholder="" />
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item class="margin-bottom-0" label="维修内容">
							<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.actualRepairDescription || '无' }}</span>
							<jk-input v-else v-model="ruleForm.actualRepairDescription" type="textarea" :rows="2" placeholder="" />
						</el-form-item>
					</el-col>
				</el-row>
			</jk-divider-card>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import {
        machineManagerRepairOrderCreate,
        machineManagerRepairOrderGet,
        machineManagerRepairOrderUpdate
    } from '../../../../api/machine/repairOrder';
    import remoteSearchMachineInput from './components/remote-search-machine-input';
    import { formatDate } from '../../../../utils/jk/jk-tool';
    import { validateArr } from '../../../../utils/jk/validator';
    export default {
        components: {
            remoteSearchMachineInput
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            repairRecord: {
                type: Boolean,
                default: false
            },
            pageType: {
                type: String,
                default: ''
            },
            machineList: {
                type: Object,
                default() {
                    return {};
                }
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data(_this) {
            return {
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    id: null,
                    belongDate: '',
                    machineId: '',
                    timeRange: [],
                    beginTime: '',
                    endTime: '',
                    upkeepState: 2,
                    faultDescription: '',
                    faultDiagnosis: '',
                    actualRepairDescription: '',
                    ifRecord: true
                },
                rules: {
                    timeRange: [{ required: true, validator: validateArr, trigger: 'change' }],
                    belongDate: [{ required: true, trigger: 'change' }],
                    machineId: [{ required: true, trigger: 'change' }],
                    endTime: [{ required: true, trigger: 'change' }],
                    beginTime: [{ required: true, trigger: 'change' }]
                },
                startPickerOption: {
                    disabledDate(e) {
                        console.log('快速', e, Date.parse(_this.ruleForm.endTime));
                        return _this.ruleForm.endTime ? Date.parse(e) > Date.parse(_this.ruleForm.endTime) : false;
                    }
                },
                endPickerOption: {
                    disabledDate(e) {
                        console.log('结束', e, Date.parse(_this.ruleForm.beginTime));
                        return _this.ruleForm.beginTime ? Date.parse(e) < Date.parse(_this.ruleForm.beginTime) : false;
                    }
                }
            };
        },
        methods: {
            onSelectMachineChange(e) {
                if (e && Object.keys(e).length) {
                    this.$set(this.ruleForm, 'machineId', e.id);
                    this.$set(this.ruleForm, 'machineCode', e.code);
                    this.$set(this.ruleForm, 'machineName', e.name);
                }
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                if (!this.dataId) params.inspectionItemId = this.machineList.id;
                if (params.timeRange && params.timeRange.length) {
                    params.beginTime = params.timeRange[0];
                    params.endTime = params.timeRange[1];
                }
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const api = !this.dataId ? machineManagerRepairOrderCreate : machineManagerRepairOrderUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return machineManagerRepairOrderGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        resData.timeRange = resData.beginTime ? [resData.beginTime, resData.endTime] : [];
                        this.ruleForm = resData;
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                }
                if (!this.ruleForm.machineName) {
                    this.$set(this.ruleForm, 'machineName', this.machineList.machineName);
                    this.$set(this.ruleForm, 'machineCode', this.machineList.machineCode);
                    this.$set(this.ruleForm, 'machineId', this.machineList.machineId);
                }
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
